package com.dctp.ems.controller;

import com.dctp.common.controller.BaseController;
import com.dctp.common.utils.DateUtil;
import com.dctp.common.utils.StringUtil;
import com.dctp.common.utils.UUIDUtil;
import com.dctp.common.cache.UserCache;
import com.dctp.common.vo.JsonResult;
import com.dctp.common.vo.PageResult;
import com.dctp.common.vo.QueryResult;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.time.LocalDateTime;

@Path("/transfer")
public class TransferController extends BaseController {

    private QueryResult buildTransferQuery() {
        Long userId = getParaToLong("user_id");
        Long toUserId = getParaToLong("to_user_id");
        String transferSn = getPara("transfer_sn", "");
        String status = getPara("status", "");
        String startTime = getPara("start_time");
        String endTime = getPara("end_time");
        StringBuilder where = new StringBuilder(" WHERE 1=1 ");
        List<Object> params = new ArrayList<>();
        if (userId != null) {
            where.append(" AND user_id = ?");
            params.add(userId);
        }
        if (toUserId != null) {
            where.append(" AND to_user_id = ?");
            params.add(toUserId);
        }
        if (!transferSn.isEmpty()) {
            where.append(" AND transfer_sn = ?");
            params.add(transferSn);
        }
        if (!status.isEmpty()) {
            where.append(" AND status = ?");
            params.add(status);
        }
        if (startTime != null && !startTime.isEmpty()) {
            where.append(" AND create_time >= ?");
            params.add(startTime);
        }
        if (endTime != null && !endTime.isEmpty()) {
            where.append(" AND create_time <= ?");
            params.add(endTime);
        }
        String filterField = getFilterField();
        Long filterUserId = getRequestUser().getLong("user_id");
        if (filterField != null && filterUserId != null) {
            where.append(" AND ").append(filterField).append(" = ?");
            params.add(filterUserId);
        }

        String roleKey = getPara("roleKey");
        Long roleUserId = getParaToLong("roleUserId");
        if (StringUtil.isNotEmpty(roleKey) && null != roleUserId) {
            where.append(" AND ").append(roleKey).append(" = ?");
            params.add(roleUserId);
        }

        return new QueryResult(where, params);
    }

    /**
     * GET /transfer/list
     * 分页查询转赠记录
     */
    public void list() {
        int page = getInt("currentPage", 1);
        int pageSize = getInt("pageSize", 10);
        QueryResult qr = buildTransferQuery();
        String select = "SELECT * ";
        String from = "FROM dctp_transfer" + qr.where + " ORDER BY id DESC";
        var p = Db.paginate(page, pageSize, select, from, qr.params.toArray());
        List<Record> list = p.getList();
        for (Record r : list) {
            Long uid = r.getLong("user_id");
            if (uid != null) {
                Record user = UserCache.getShowInfo(uid);
                r.set("user", user != null ? user.getColumns() : null);
            }

            Long toUserId = r.getLong("to_user_id");
            if (toUserId != null) {
                Record user = UserCache.getShowInfo(toUserId);
                r.set("toUser", user != null ? user.toMap() : null);
            }
        }
        renderJson(JsonResult.successWithData(
            new PageResult<>(list, p.getTotalRow(), pageSize, page)
        ));
    }

    /**
     * GET /transfer/export
     * 导出转赠记录Excel，支持user_id、to_user_id、transfer_sn、status、create_time范围
     */
    public void export() {
        QueryResult qr = buildTransferQuery();
        String sql = "SELECT * FROM dctp_transfer" + qr.where + " ORDER BY id DESC";
        List<Record> list = Db.find(sql, qr.params.toArray());
        try (Workbook wb = new XSSFWorkbook()) {
            Sheet sheet = wb.createSheet("转赠记录");
            int rowIdx = 0;
            Row head = sheet.createRow(rowIdx++);
            String[] fields = {"id", "transfer_sn", "user_id", "to_user_id", "amount", "currency", "status", "remark", "create_time"};
            String[] titles = {"ID", "转赠流水号", "转出用户ID", "转入用户ID", "金额", "币种", "状态", "备注", "创建时间"};
            for (int i = 0; i < titles.length; i++) head.createCell(i).setCellValue(titles[i]);
            for (Record r : list) {
                Row row = sheet.createRow(rowIdx++);
                Long uid = r.getLong("user_id");
                Long toUid = r.getLong("to_user_id");
                Record user = uid != null ? UserCache.getBasic(uid) : null;
                Record toUser = toUid != null ? UserCache.getBasic(toUid) : null;
                for (int i = 0; i < fields.length; i++) {
                    Object val;
                    switch (fields[i]) {
                        case "user_id":
                            val = uid != null ? uid : "";
                            break;
                        case "to_user_id":
                            val = toUid != null ? toUid : "";
                            break;
                        case "amount":
                            val = r.getBigDecimal("amount") != null ? r.getBigDecimal("amount").toPlainString() : "";
                            break;
                        case "create_time": {
                            LocalDateTime createTime = r.getLocalDateTime("create_time");
                            val = createTime != null ? DateUtil.format(createTime) : "";
                            break;
                        }
                        default:
                            val = r.get(fields[i]) != null ? r.get(fields[i]) : "";
                    }
                    row.createCell(i).setCellValue(val.toString());
                }
                // 用户账号单独处理
                row.createCell(2).setCellValue(user != null ? user.getStr("login_account") : "");
                row.createCell(3).setCellValue(toUser != null ? toUser.getStr("login_account") : "");
            }
            String dateStr = DateUtil.format(DateUtil.now(), "yyyyMMdd");
            String randomStr = UUIDUtil.orderedUUID().substring(0, 8);
            String fileName = "转赠记录-" + dateStr + "-" + randomStr + ".xlsx";
            HttpServletResponse resp = getResponse();
            resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            wb.write(resp.getOutputStream());
            renderNull();
        } catch (Exception e) {
            throw new RuntimeException("导出失败", e);
        }
    }
}
